package com.example.mqtt_demo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {
    private var mAdapter: MessageAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ReceiverMessageHelper.startReceiverThread()
        mAdapter = MessageAdapter()

        val recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = mAdapter

        ReceiverMessageHelper.messagePublisher.observe(this, {
            var message = MessageData(it, true)
            mAdapter?.insertMessage(message)
        })
    }

    private class MessageAdapter : RecyclerView.Adapter<MessageHolder>() {
        private val SENDER = 0
        private val RECEIVER = 0

        private val mData = mutableListOf<MessageData>()

        override fun getItemViewType(position: Int): Int {
            return if (mData[position].isReceiver) {
                RECEIVER
            } else {
                SENDER
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageHolder {
            val layoutInflater = LayoutInflater.from(parent.context)
            val itemView = layoutInflater.inflate(R.layout.message_item, parent, false)
            val messageContainer = itemView.findViewById<LinearLayout>(R.id.message_container)
            val messageText = itemView.findViewById<TextView>(R.id.message_text)

            if (viewType == SENDER) {
                messageContainer.gravity = Gravity.LEFT
                messageText.setBackgroundResource(R.drawable.message_send_shape)
            } else {
                messageContainer.gravity = Gravity.RIGHT
                messageText.setBackgroundResource(R.drawable.message_receiver_shape)
            }

            return MessageHolder(itemView)
        }

        override fun onBindViewHolder(holder: MessageHolder, position: Int) {
            holder.bindData(mData[position])
        }

        override fun getItemCount() = mData.size

        fun insertMessage(message: MessageData) {
            mData.add(message)
            notifyItemInserted(mData.size)
        }
    }

    private class MessageHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bindData(message: MessageData) {
            val messageText = itemView.findViewById<TextView>(R.id.message_text)
            messageText.text = message.message
        }

    }
}